<template>
  <view class="container">
    <!-- 顶部装饰元素 -->
    <view class="top-decoration"></view>
    
    <view class="quiz-container">
      
      <!-- 题目数量和计时器 -->
      <view class="header">
        <view class="progress">
          <text>第 {{ currentIndex + 1 }} / {{ questions.length }} 题</text>
        </view>
        <view class="timer" :class="{ warning: timeRemaining < 4 }">
          <text>⏱️ 剩余时间: {{ timeRemaining }}s</text>
        </view>
      </view>
      
      <!-- 题目展示区 -->
      <view class="question-card">
        <view class="question">
          <text class="number">{{ currentQuestion.a }}</text>
          <text class="operator">+</text>
          <text class="number">{{ currentQuestion.b }}</text>
          <text class="equal">=</text>
          <input 
            type="number" 
            v-model="userAnswer" 
            class="answer-input" 
            placeholder="?"
            @confirm="checkAnswer"
            @input="handleInput"
            :disabled="timeUp || answerCorrect"
          />
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <button 
        class="submit-btn" 
        @click="checkAnswer"
        :disabled="!userAnswer || timeUp || answerCorrect"
        :class="{ disabled: !userAnswer || timeUp || answerCorrect }"
      >
        提交答案
      </button>
      
      <!-- 结果提示 -->
      <view 
        class="result" 
        :class="{ 
          correct: lastResult === 'correct', 
          wrong: lastResult === 'wrong' || lastResult === 'timeout' 
        }"
        v-if="lastResult && (lastResult !== 'wrong' || showWrongHint)"
      >
        <text v-if="lastResult === 'correct'">🎉 正确！</text>
        <text v-if="lastResult === 'wrong'">❌ 错误，正确答案是 {{ lastCorrectAnswer }}</text>
        <text v-if="lastResult === 'timeout'">⏰ 时间到！正确答案是 {{ lastCorrectAnswer }}</text>
      </view>
    </view>
    
    <!-- 底部装饰元素 -->
    <view class="bottom-decoration"></view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      questions: [], // 存储所有题目
      currentIndex: 0, // 当前题目索引
      userAnswer: '', // 用户输入的答案
      lastResult: '', // 上一题的结果：correct/wrong/timeout
      lastCorrectAnswer: 0, // 上一题的正确答案
      timeRemaining: 10, // 剩余时间（秒）
      timer: null, // 计时器
      timeUp: false, // 时间是否已到
      startTime: 0, // 开始时间
      totalTime: 0, // 总用时
      score: 0, // 得分
      answerCorrect: false, // 答案是否正确
      showWrongHint: false // 是否显示错误提示
    };
  },
  
  onLoad() {
    // 页面初始化时生成10道题目
    this.generateQuestions(10);
    this.startTime = Date.now();
    this.startTimer();
  },
  
  onUnload() {
    // 页面卸载时清除计时器
    this.clearTimer();
  },
  
  computed: {
    // 获取当前题目
    currentQuestion() {
      return this.questions[this.currentIndex] || {};
    }
  },
  
  methods: {
    // 返回按钮处理方法
    handleBack() {
      // 显示确认对话框
      uni.showModal({
        title: '返回确认',
        content: '确定要退出当前测验吗？',
        cancelText: '取消',
        confirmText: '确定',
        success: (res) => {
          if (res.confirm) {
            // 确认返回，这里使用uni.navigateBack()或其他适合的导航方法
            uni.navigateBack({
              delta: 1
            });
          }
        }
      });
    },
    
    // 生成指定数量的题目
    generateQuestions(count) {
      this.questions = [];
      for (let i = 0; i < count; i++) {
        // 生成两个1-99之间的随机整数
        const a = Math.floor(Math.random() * 99) + 1;
        const b = Math.floor(Math.random() * 99) + 1;
        this.questions.push({
          a,
          b,
          answer: a + b
        });
      }
    },
    
    // 开始计时器
    startTimer() {
      this.timeRemaining = 10;
      this.timeUp = false;
      this.answerCorrect = false;
      this.showWrongHint = false;
      this.userAnswer = '';
      this.lastResult = '';
      
      this.clearTimer();
      
      this.timer = setInterval(() => {
        this.timeRemaining--;
        
        if (this.timeRemaining <= 0) {
          this.timeUp = true;
          this.clearTimer();
          // 时间到，记录结果为超时，并保存正确答案
          this.lastResult = 'timeout';
          this.lastCorrectAnswer = this.currentQuestion.answer;
          
          // 1秒后进入下一题
          setTimeout(() => {
            this.nextQuestion();
          }, 1000);
        }
      }, 1000);
    },
    
    // 清除计时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    
    // 处理输入
    handleInput() {
      // 输入完成后自动验证（如果输入不为空且答案尚未正确）
      if (this.userAnswer && !this.answerCorrect && !this.timeUp) {
        // 使用setTimeout确保v-model已更新
        setTimeout(() => {
          this.checkAnswer(true);
        }, 300); // 稍作延迟，等待用户输入完成
      }
    },
    
    // 检查答案
    checkAnswer(autoCheck = false) {
      // 如果时间已到、没有答案或答案已正确，不执行
      if (this.timeUp || !this.userAnswer || this.answerCorrect) return;
      
      const answer = parseInt(this.userAnswer);
      const correct = answer === this.currentQuestion.answer;
      
      if (correct) {
        // 答案正确
        this.answerCorrect = true;
        this.lastResult = 'correct';
        this.score++;
        
        // 清除计时器
        this.clearTimer();
        
        // 显示正确提示后进入下一题
        setTimeout(() => {
          this.nextQuestion();
        }, 800);
      } else {
        // 答案错误 - 仅在手动提交时显示错误提示
        this.lastResult = 'wrong';
        this.lastCorrectAnswer = this.currentQuestion.answer;
        if (!autoCheck) {
          this.showWrongHint = true;
        }
        // 不跳转，允许用户继续输入
      }
    },
    
    // 进入下一题
    nextQuestion() {
      // 检查是否是最后一题
      if (this.currentIndex < this.questions.length - 1) {
        this.currentIndex++;
        this.startTimer();
      } else {
        // 完成所有题目，计算总用时
        this.totalTime = Math.floor((Date.now() - this.startTime) / 1000);
        
        // 显示结果弹窗
        uni.showModal({
          title: '🎉 测验完成',
          content: `总用时: ${this.totalTime}秒\n答对数量: ${this.score}/${this.questions.length}`,
          showCancel: false,
          confirmText: '再来一次',
          success: () => {
            this.restartQuiz();
          }
        });
      }
    },
    
    // 重新开始测验
    restartQuiz() {
      this.clearTimer();
      this.generateQuestions(10);
      this.currentIndex = 0;
      this.userAnswer = '';
      this.lastResult = '';
      this.score = 0;
      this.answerCorrect = false;
      this.startTime = Date.now();
      this.startTimer();
    }
  }
};
</script>

<style scoped>
/* 全局样式 */
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  padding: 20rpx;
  position: relative;
  overflow: hidden;
}

/* 装饰元素 */
.top-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background: linear-gradient(45deg, #4cd964 0%, #5ac8fa 100%);
  border-bottom-left-radius: 50% 20%;
  border-bottom-right-radius: 50% 20%;
  z-index: 1;
}

.bottom-decoration {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 80rpx;
  background: linear-gradient(135deg, #4cd964 0%, #5ac8fa 100%);
  border-top-left-radius: 50% 30%;
  border-top-right-radius: 50% 30%;
  z-index: 1;
}

/* 返回按钮样式 */
.back-button {
  display: flex;
  align-items: center;
  color: #5ac8fa;
  background-color: rgba(90, 200, 250, 0.1);
  border-radius: 30rpx;
  padding: 8rpx 20rpx;
  margin-bottom: 40rpx;
  width: fit-content;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.back-button:hover {
  background-color: rgba(90, 200, 250, 0.2);
  transform: translateX(-3rpx);
}

.back-icon {
  font-size: 34rpx;
  margin-right: 8rpx;
  font-weight: bold;
}

.back-text {
  font-size: 30rpx;
}

/* 测验容器 */
.quiz-container {
  background-color: #fff;
  border-radius: 30rpx;
  padding: 60rpx 40rpx;
  margin: 80rpx 20rpx 120rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 2;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 头部信息 */
.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 80rpx;
  align-items: center;
}

.progress {
  color: #555;
  font-size: 30rpx;
  padding: 10rpx 20rpx;
  background-color: #f0f7ff;
  border-radius: 30rpx;
  font-weight: 500;
}

.timer {
  color: #3498db;
  font-size: 30rpx;
  padding: 12rpx 24rpx;
  border-radius: 30rpx;
  background-color: #f0f7ff;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8rpx;
  transition: all 0.3s ease;
}

.timer.warning {
  color: #e74c3c;
  background-color: #fff5f5;
  animation: pulse 1s infinite alternate;
}

/* 题目卡片 */
.question-card {
  background: linear-gradient(145deg, #f9f9f9 0%, #f0f7ff 100%);
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
  margin-bottom: 60rpx;
  box-shadow: 0 4rpx 15rpx rgba(90, 200, 250, 0.1);
  border: 1px solid #f0f0f0;
}

/* 题目样式 */
.question {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0;
  flex-wrap: wrap;
  gap: 30rpx;
}

.number {
  font-size: 60rpx;
  color: #333;
  min-width: 80rpx;
  text-align: center;
  font-weight: 600;
  transition: transform 0.2s ease;
}

.number:active {
  transform: scale(1.05);
}

.operator, .equal {
  font-size: 54rpx;
  color: #5ac8fa;
  font-weight: bold;
}

.equal {
  color: #4cd964;
}

/* 答案输入框 */
.answer-input {
  width: 180rpx;
  height: 90rpx;
  border: 3rpx solid #5ac8fa;
  border-radius: 12rpx;
  font-size: 54rpx;
  text-align: center;
  margin-left: 0;
  background-color: #fff;
  transition: all 0.3s ease;
  font-weight: 600;
  color: #333;
}

.answer-input:focus {
  border-color: #4cd964;
  box-shadow: 0 0 0 6rpx rgba(76, 217, 100, 0.2);
  outline: none;
}

.answer-input:disabled {
  background-color: #f9f9f9;
  border-color: #ddd;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  background: linear-gradient(90deg, #5ac8fa 0%, #4cd964 100%);
  color: #fff;
  font-size: 34rpx;
  border-radius: 50rpx;
  margin-bottom: 40rpx;
  border: none;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 6rpx 15rpx rgba(90, 200, 250, 0.3);
}

.submit-btn:not(.disabled):hover, .submit-btn:not(.disabled):active {
  transform: translateY(-3rpx);
  box-shadow: 0 10rpx 20rpx rgba(90, 200, 250, 0.4);
  background: linear-gradient(90deg, #4aa9e0 0%, #3dc054 100%);
}

.submit-btn.disabled {
  background: #e0e0e0;
  color: #999;
  box-shadow: none;
  transform: none;
}

/* 结果提示 */
.result {
  text-align: center;
  font-size: 36rpx;
  padding: 25rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  font-weight: 500;
  animation: fadeIn 0.5s ease;
}

.correct {
  background-color: #f0fff4;
  color: #00b42a;
  border: 1px solid #c9f0d3;
}

.wrong {
  background-color: #fff5f5;
  color: #f53f3f;
  border: 1px solid #ffe0e0;
}

/* 动画效果 */
@keyframes pulse {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(1.05);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
    